package com.rpp.listener;

import com.rabbitmq.client.Channel;
import com.rpp.service.IOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author peng
 * @Date 2020/10/28 4:10 下午
 */
@Component
public class RabbitMqListener {

    @Autowired
    IOrderService orderService;

    /**
     * @Payload 注解方法参数，改参数的值就是消息体
     * @Header 注解方法参数，访问指定的消息头字段的值
     * @Headers 该注解的方法参数获取该消息的消息头的所有字段，参数类型对应于map集合。
     * MessageHeaders 参数类型，访问所有消息头字段
     * MessageHeaderAccessor or AmqpMessageHeaderAccessor 访问所有消息头字段
     */
    @RabbitListener(queues = "q.order.dlx", ackMode = "MANUAL")
    public void whenMessageCome(Message message, Channel channel) throws Exception {
        String body = new String(message.getBody(), "utf-8");
        System.out.println("接收到消息:" + body);
        try {
            Long orderId = Long.parseLong(body);

            Boolean result = orderService.closeOrder(orderId);
            if (result) {
                System.out.println("消息消费成功");
                //确认消息消费成功
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                System.out.println("消息消费失败，重新放入队列");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //消息丢弃
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}